#include "home.h"
#include "ui_home.h"
#include "QInputDialog"
#include "QMessageBox"
#include "TcpHelper.h"
#include "client.h"
#include "chatdialog.h"
#include "QTimer"
#include "QCloseEvent"
#include "tcptaskthread.h"

home::home(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::home)
{
    ui->setupUi(this);
    ui->label->setText("您好，"+me.user_name);

    TcpHelper helper;

    // 创建并启动 TcpTaskThread
    TcpTaskThread *taskThread = new TcpTaskThread();
    taskThread->start();

    // 获取 TcpTask 对象
    TcpTask *task1 = taskThread->getTcpTask();

    home::connect(task1, &TcpTask::UserInformationReady, [=](User user){
        me = user;
    });

    task1->sendCommand(helper.getUserIdForInformationTask(myId));

    home::refreshFriendList();

    home::connect(ui->toolButton_fresh, &QToolButton::clicked, this, &home::refreshFriendList);
}

home::~home()
{
    delete ui;
}

void home::closeEvent(QCloseEvent *event)
{
    TcpHelper helper;

    // 创建并启动 TcpTaskThread
    TcpTaskThread *taskThread = new TcpTaskThread();
    taskThread->start();

    // 获取 TcpTask 对象
    TcpTask *task8 = taskThread->getTcpTask();

    me.user_status = NOT_ONLINE;

    task8->sendCommand(helper.getUpdateUserInformationTask(me));

    event->accept();
    this->close();
    client *cli = new client();
    cli->show();
}


void home::refreshFriendList()
{
    qDebug()<<"fresh";
    TcpHelper helper;

    // 创建并启动 TcpTaskThread
    TcpTaskThread *taskThread = new TcpTaskThread();
    taskThread->start();

    // 获取 TcpTask 对象
    TcpTask *task2 = taskThread->getTcpTask();

    home::connect(task2, &TcpTask::FriendListReady, [=](QList<Friend> friendList){
        ui->listWidget->clear();

        for (const Friend &friendItem : friendList) {
            TcpHelper helper;

            // 创建并启动 TcpTaskThread
            TcpTaskThread *taskThread = new TcpTaskThread();
            taskThread->start();

            // 获取 TcpTask 对象
            TcpTask *task3 = taskThread->getTcpTask();

            home::connect(task3, &TcpTask::UserInformationReady, [=](User user){
                myFriend = user;
            });

            task3->sendCommand(helper.getUserIdForInformationTask(friendItem.friend_id));

            QListWidgetItem *item = new QListWidgetItem();
            item->setText(myFriend.user_name + "          " + (myFriend.user_status == ONLINE ? "在线" : "离线"));
            if (myFriend.user_status == ONLINE) {
                item->setBackground(Qt::green);
            } else{
                item->setBackground(Qt::red);
            }

            ui->listWidget->addItem(item);

            myFriendList.append(myFriend);
            listnum++;
        }
    });

    home::connect(task2, &TcpTask::FriendListError, [=](){
        listnum = 0;
        ui->listWidget->clear();
        ui->listWidget->insertItem(0,tr("您还没有朋友"));
        ui->toolButton_startChat->setEnabled(false);
        ui->toolButton_deletePeople->setEnabled(false);
    });

    task2->sendCommand(helper.getUserIdForFriendListTask(myId));
}

void home::on_toolButton_addPeople_clicked()
{
    bool ok;
    QString addfriendID = QInputDialog::getText(this, tr("增添联系人"),tr("请输入对方ID"), QLineEdit::Normal,0,&ok);
    myFriend.id = addfriendID.toInt();
    if (ok && !addfriendID.isEmpty())
    {

        if(addfriendID.toInt() != me.id)
        {
            TcpHelper helper;

            // 创建并启动 TcpTaskThread
            TcpTaskThread *taskThread = new TcpTaskThread();
            taskThread->start();

            // 获取 TcpTask 对象
            TcpTask *task4 = taskThread->getTcpTask();

            home::connect(task4, &TcpTask::insertFriendRelationOk, [=](){
                QMessageBox::warning(this, "Warning!", "添加成功", QMessageBox::Yes);
                ui->toolButton_startChat->setEnabled(true);
                ui->toolButton_deletePeople->setEnabled(true);
            });

            home::connect(task4, &TcpTask::insertFriendRelationError, [=](){
                QMessageBox::warning(this, "Warning!", "查无此人", QMessageBox::Yes);
            });

            task4->sendCommand(helper.getInsertFriendRelationTask(me.id, myFriend.id));
        }
        else
        {
            QMessageBox::warning(this, "Warning!", "不能添加自己", QMessageBox::Yes);
        }
    }
}


void home::on_toolButton_deletePeople_clicked()
{
    if(ui->listWidget->currentRow()!=-1)
    {
        myFriend = myFriendList.at(ui->listWidget->currentRow());
        QString dlgTitle="提示";
        QString strInfo="您将删除好友："+myFriend.user_name+"\n确定吗？";
        QMessageBox::StandardButton  defaultBtn=QMessageBox::NoButton;
        QMessageBox::StandardButton result;
        result=QMessageBox::question(this, dlgTitle, strInfo,QMessageBox::Cancel|QMessageBox::Yes,defaultBtn);
        if (result==QMessageBox::Yes)
        {
            TcpHelper helper;

            // 创建并启动 TcpTaskThread
            TcpTaskThread *taskThread = new TcpTaskThread();
            taskThread->start();

            // 获取 TcpTask 对象
            TcpTask *task5 = taskThread->getTcpTask();

            home::connect(task5, &TcpTask::DeleteFriendRelationOk, [=](){
                QMessageBox::warning(this, "Warning!", "删除联系人成功", QMessageBox::Yes);
            });

            home::connect(task5, &TcpTask::DeleteFriendRelationError, [=](){
                QMessageBox::warning(this, "Warning!", "删除联系人失败", QMessageBox::Yes);
            });

            task5->sendCommand(helper.getDeleteFriendRelationTask(me.id, myFriend.id));
        }
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}


void home::on_toolButton_quit_clicked()
{
    TcpHelper helper;

    // 创建并启动 TcpTaskThread
    TcpTaskThread *taskThread = new TcpTaskThread();
    taskThread->start();

    // 获取 TcpTask 对象
    TcpTask *task7 = taskThread->getTcpTask();

    me.user_status = NOT_ONLINE;

    task7->sendCommand(helper.getUpdateUserInformationTask(me));

    this->close();
    client *cli = new client();
    cli->show();
}


void home::on_toolButton_startChat_clicked()
{
    if(ui->listWidget->currentRow()!=-1)
    {
        myFriend = myFriendList.at(ui->listWidget->currentRow());
        ChatDialog *cht = new ChatDialog();
        cht->show();
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}


void home::on_toolButton_sendMessage_clicked()
{
    if(ui->lineEdit_sendId->text()!="" && ui->lineEdit_sendId->text().toInt()!=myId)
    {//发送人名不为空,且不能给自己发送消息
        TcpHelper helper;

        // 创建并启动 TcpTaskThread
        TcpTaskThread *taskThread = new TcpTaskThread();
        taskThread->start();

        // 获取 TcpTask 对象
        TcpTask *task6 = taskThread->getTcpTask();
        home::connect(task6, &TcpTask::UserInformationReady, [=](User user){
            myFriend = user;
            ui->lineEdit_sendId->clear();
            ChatDialog *cht = new ChatDialog();
            cht->show();
        });

        home::connect(task6, &TcpTask::UserInformationError, [=](){
            QMessageBox::warning(this, "Warning!", "查无此人", QMessageBox::Yes);
            ui->lineEdit_sendId->clear();
            ui->lineEdit_sendId->setFocus();
        });

        task6->sendCommand(helper.getUserIdForInformationTask(ui->lineEdit_sendId->text().toInt()));
    }
    else if(ui->lineEdit_sendId->text()==me.user_name)
    {
        QMessageBox::warning(this, "Warning!", "不能给自己发消息", QMessageBox::Yes);
        ui->lineEdit_sendId->clear();
        ui->lineEdit_sendId->setFocus();
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "用户名不为空", QMessageBox::Yes);
        ui->lineEdit_sendId->clear();
        ui->lineEdit_sendId->setFocus();
    }
}
